package org.termine.logic;

import java.io.Serializable;
import java.sql.Connection;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;

import org.slf4j.LoggerFactory;
import org.termine.dao.LocationDAO;
import org.termine.dao.PersonalDataDAO;
import org.termine.entity.Location;
import org.termine.entity.PersonalData;
import org.termine.util.GeoCoder;

@ManagedBean
@ApplicationScoped
public class LocationManager extends BaseManager implements Serializable {

	private static final long serialVersionUID = -4391901821108104637L;

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(LocationManager.class);

	@ManagedProperty(value = "#{locationDAO}")
	private LocationDAO locationDAO;
	@ManagedProperty(value = "#{personalDataDAO}")
	private PersonalDataDAO personalDataDAO;

	public Location getLocation(Integer locationId) {
		Connection connection = null;
		try {
			connection = this.connector.getConnection();
			return this.getLocationDAO().getLocation(connection, locationId);
		} catch (Exception e) {
			logger.error("ERROR: ", e);
			return null;
		} finally {
			this.connector.closeConnection(connection);
		}
	}

	public boolean updateLocation(Location location, PersonalData personalData) {
		Connection connection = null;
		try {
			connection = this.connector.getConnection();
			Integer locationId = this.getLocationDAO().getLocationId(connection, location);
			if (locationId == null) {
				GeoCoder.setPosition(location);
				this.getLocationDAO().addLocation(connection, location);
				locationId = this.getLocationDAO().getLocationId(connection, location);
				personalData.setLocation_id(locationId);
				this.getPersonalDataDAO().updatePersonalData(connection, personalData);
			} else {
				personalData.setLocation_id(locationId);
				this.getPersonalDataDAO().updatePersonalData(connection, personalData);
			}
			this.connector.commit(connection);
			return true;
		} catch (Exception e) {
			this.connector.rollback(connection);
			logger.error("ERROR: ", e);
			return false;
		}
	}

	/*
	 * Getters & Setters
	 */
	public LocationDAO getLocationDAO() {
		return this.locationDAO;
	}

	public void setLocationDAO(LocationDAO locationDAO) {
		this.locationDAO = locationDAO;
	}

	public PersonalDataDAO getPersonalDataDAO() {
		return this.personalDataDAO;
	}

	public void setPersonalDataDAO(PersonalDataDAO personalDataDAO) {
		this.personalDataDAO = personalDataDAO;
	}

}
